/**
 * 简单路由模块
 * 提供页面导航和路由处理功能，为后续框架迁移做准备
 */

class Router {
    constructor() {
        this.routes = [];
        this.currentRoute = null;
        this.isHistoryMode = false;
        this.basePath = '';
    }

    /**
     * 初始化路由
     * @param {Object} options - 路由配置选项
     * @param {boolean} options.historyMode - 是否使用history模式
     * @param {string} options.basePath - 基础路径
     */
    init(options = {}) {
        this.isHistoryMode = options.historyMode || false;
        this.basePath = options.basePath || '';
        
        // 注册路由事件监听器
        this.setupEventListeners();
        
        // 初始路由匹配
        this.handleRoute();
    }

    /**
     * 注册路由
     * @param {string} path - 路由路径
     * @param {Function} callback - 路由匹配时的回调函数
     * @param {Object} options - 路由选项
     * @returns {Router} 返回router实例以支持链式调用
     */
    add(path, callback, options = {}) {
        this.routes.push({
            path: this.normalizePath(path),
            callback,
            exact: options.exact !== false, // 默认精确匹配
            name: options.name
        });
        return this;
    }

    /**
     * 注册多个路由
     * @param {Array} routesConfig - 路由配置数组
     * @returns {Router} 返回router实例以支持链式调用
     */
    addRoutes(routesConfig) {
        routesConfig.forEach(route => {
            this.add(route.path, route.callback, route.options || {});
        });
        return this;
    }

    /**
     * 导航到指定路径
     * @param {string} path - 目标路径
     * @param {Object} options - 导航选项
     */
    navigate(path, options = {}) {
        const normalizedPath = this.normalizePath(path);
        
        if (this.isHistoryMode) {
            // 使用history API
            const fullPath = this.basePath + normalizedPath;
            if (options.replace) {
                history.replaceState(null, '', fullPath);
            } else {
                history.pushState(null, '', fullPath);
            }
            this.handleRoute();
        } else {
            // 使用hash模式
            window.location.hash = normalizedPath;
        }
    }

    /**
     * 替换当前路由
     * @param {string} path - 目标路径
     */
    replace(path) {
        this.navigate(path, { replace: true });
    }

    /**
     * 后退
     */
    back() {
        history.back();
    }

    /**
     * 前进
     */
    forward() {
        history.forward();
    }

    /**
     * 刷新当前路由
     */
    refresh() {
        this.handleRoute();
    }

    /**
     * 获取当前路径参数
     * @returns {Object} 参数对象
     */
    getParams() {
        if (!this.currentRoute) return {};
        
        const path = this.getCurrentPath();
        const route = this.routes.find(r => this.matchPath(r.path, path));
        
        if (!route) return {};
        
        return this.extractParams(route.path, path);
    }

    /**
     * 获取当前查询参数
     * @returns {Object} 查询参数对象
     */
    getQuery() {
        const queryString = window.location.search.slice(1);
        const params = new URLSearchParams(queryString);
        const query = {};
        
        for (const [key, value] of params.entries()) {
            query[key] = value;
        }
        
        return query;
    }

    /**
     * 获取当前路径
     * @returns {string} 当前路径
     */
    getCurrentPath() {
        if (this.isHistoryMode) {
            const path = window.location.pathname;
            return path.startsWith(this.basePath) ? 
                path.slice(this.basePath.length) : path;
        } else {
            return window.location.hash.slice(1) || '/';
        }
    }

    /**
     * 处理路由匹配和回调
     * @private
     */
    handleRoute() {
        const path = this.getCurrentPath();
        let matchedRoute = null;
        
        // 尝试精确匹配
        matchedRoute = this.routes.find(route => 
            route.exact && this.matchPath(route.path, path)
        );
        
        // 如果没有精确匹配，尝试非精确匹配
        if (!matchedRoute) {
            matchedRoute = this.routes.find(route => 
                !route.exact && this.matchPath(route.path, path)
            );
        }
        
        // 如果找到匹配的路由，执行回调
        if (matchedRoute) {
            this.currentRoute = matchedRoute;
            const params = this.extractParams(matchedRoute.path, path);
            const query = this.getQuery();
            
            try {
                matchedRoute.callback({ 
                    path, 
                    params, 
                    query,
                    route: matchedRoute
                });
            } catch (error) {
                console.error('Error executing route callback:', error);
            }
        } else {
            // 未找到匹配的路由，尝试处理404
            this.handleNotFound(path);
        }
    }

    /**
     * 设置事件监听器
     * @private
     */
    setupEventListeners() {
        // 监听popstate事件（history模式）
        window.addEventListener('popstate', () => {
            this.handleRoute();
        });
        
        // 监听hashchange事件（hash模式）
        if (!this.isHistoryMode) {
            window.addEventListener('hashchange', () => {
                this.handleRoute();
            });
        }
        
        // 处理页面内导航链接
        document.addEventListener('click', (e) => {
            const target = e.target.closest('a[router-link]');
            if (target) {
                e.preventDefault();
                const path = target.getAttribute('router-link') || target.getAttribute('href');
                this.navigate(path);
            }
        });
    }

    /**
     * 路径规范化
     * @private
     * @param {string} path - 路径
     * @returns {string} 规范化后的路径
     */
    normalizePath(path) {
        // 确保路径以/开头
        let normalized = path.trim();
        if (!normalized.startsWith('/')) {
            normalized = '/' + normalized;
        }
        
        // 移除末尾的/
        if (normalized.length > 1 && normalized.endsWith('/')) {
            normalized = normalized.slice(0, -1);
        }
        
        return normalized;
    }

    /**
     * 路径匹配
     * @private
     * @param {string} routePath - 路由路径
     * @param {string} currentPath - 当前路径
     * @returns {boolean} 是否匹配
     */
    matchPath(routePath, currentPath) {
        // 精确匹配模式
        if (routePath === currentPath) {
            return true;
        }
        
        // 处理动态路由参数，如 /post/:id
        if (routePath.includes(':')) {
            const routeSegments = routePath.split('/');
            const pathSegments = currentPath.split('/');
            
            if (routeSegments.length !== pathSegments.length) {
                return false;
            }
            
            return routeSegments.every((segment, index) => {
                return segment.startsWith(':') || segment === pathSegments[index];
            });
        }
        
        // 非精确匹配模式（前缀匹配）
        if (!routePath.endsWith('/')) {
            routePath += '/';
        }
        
        return currentPath.startsWith(routePath);
    }

    /**
     * 提取路径参数
     * @private
     * @param {string} routePath - 路由路径
     * @param {string} currentPath - 当前路径
     * @returns {Object} 提取的参数
     */
    extractParams(routePath, currentPath) {
        const params = {};
        const routeSegments = routePath.split('/');
        const pathSegments = currentPath.split('/');
        
        routeSegments.forEach((segment, index) => {
            if (segment.startsWith(':')) {
                const paramName = segment.slice(1);
                params[paramName] = pathSegments[index];
            }
        });
        
        return params;
    }

    /**
     * 处理未找到的路由
     * @private
     * @param {string} path - 未匹配的路径
     */
    handleNotFound(path) {
        console.warn(`No route found for path: ${path}`);
        // 可以在这里实现404页面跳转
        // this.navigate('/404');
    }

    /**
     * 生成带参数的路径
     * @param {string} path - 路由路径模板
     * @param {Object} params - 参数对象
     * @returns {string} 生成的路径
     */
    generatePath(path, params = {}) {
        let generatedPath = path;
        
        Object.entries(params).forEach(([key, value]) => {
            const placeholder = `:${key}`;
            if (generatedPath.includes(placeholder)) {
                generatedPath = generatedPath.replace(placeholder, value);
            }
        });
        
        return generatedPath;
    }

    /**
     * 销毁路由实例
     */
    destroy() {
        // 移除事件监听器
        window.removeEventListener('popstate', this.handleRoute.bind(this));
        window.removeEventListener('hashchange', this.handleRoute.bind(this));
        
        // 清空路由
        this.routes = [];
        this.currentRoute = null;
    }
}

// 创建单例实例
const router = new Router();

// 导出router实例
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
    module.exports = router;
} else {
    window.router = router;
}

/**
 * 使用示例：
 * 
 * // 初始化路由
 * router.init({
 *   historyMode: true,
 *   basePath: '/blog'
 * });
 * 
 * // 注册路由
 * router
 *   .add('/', () => {
 *     console.log('Home page');
 *     loadHomePage();
 *   })
 *   .add('/about', () => {
 *     console.log('About page');
 *     loadAboutPage();
 *   })
 *   .add('/post/:id', (route) => {
 *     console.log('Post page:', route.params.id);
 *     loadPostPage(route.params.id);
 *   })
 *   .add('/contact', () => {
 *     console.log('Contact page');
 *     loadContactPage();
 *   });
 * 
 * // 页面内导航
 * // HTML: <a href="#" router-link="/about">关于我们</a>
 * 
 * // 编程式导航
 * // router.navigate('/post/123');
 * // router.replace('/404');
 * // router.back();
 */